import java.io.*;
import java.util.Scanner;

/**
 * @Author YuanYuan
 * @Date 2022/10/8
 * @Time 13:40
 */
public class Demo3 {
    /**
     * 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
     * @return
    */

    public static void scanDirAndFirm() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入指定目录:");
        File dirfile = new File(scanner.next());
        if(!dirfile.isDirectory()) {
            System.out.println("不存在该目录");
            return;
        }
        System.out.println("请输入要查找文件包含指定字符:");
        String findname = scanner.next();
        //System.out.println(findname);
        //扫描文件夹
        scanFile(dirfile,findname);

    }
    private static void scanFile(File dirfile,String findname) throws IOException {
        File[] files = dirfile.listFiles();
        if(null == files) {
            return;
        }
        for (File f:
             files) {
            //如果是目录递归查看
            if(f.isDirectory()) {
                //System.out.println(f.getCanonicalPath());
                scanFile(f,findname);
            }else {
                //文件判断是否需要找到
                isFileFind(f,findname);
            }
        }
    }

    private static void isFileFind(File f, String findname) throws IOException {
        if(f.getName().contains(findname)) {
            System.out.println(f.getCanonicalPath()+"包含"+ findname);
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(f)) {
            Scanner scanner = new Scanner(inputStream);
            while (scanner.hasNextLine()) {
                //一行一行读
                stringBuilder.append(scanner.nextLine() + "\n");
            }
            if(stringBuilder.indexOf(findname) > -1) {
                System.out.println(f.getCanonicalPath()+" 文件内容包含 "+ findname);
            }
        }

    }

    public static void main(String[] args) throws IOException {
        scanDirAndFirm();
    }
}
